package com.yonyou.crm.sact.visitrule.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.common.rest.constant.HttpKeyConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.sact.visitrule.entity.RefIndexEnum;
import com.yonyou.crm.sact.visitrule.entity.VisitruleTaskcardVO;
import com.yonyou.crm.sact.visitrule.entity.VisitruleVO;
import com.yonyou.crm.sact.visitrule.rmitf.IVisitruleRmService;

@RestController
@RequestMapping(value = "/sact/visitrules")
public class VisitruleCtrl {

	@Autowired
	private IVisitruleRmService service;

	/**
	 * 查询拜访规则
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
//	@RequestMapping(method = RequestMethod.GET)
//	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
//
//		JSONObject paramObj = RequestUtil.getParamObject(request);
//
//		@SuppressWarnings("unchecked")
//		Page<VisitruleVO> productPage = service.list(getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
//		
//		return ResponseUtil.getObject(productPage);
//	}
	
	/**
	 * 查询拜访规则详情
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException 
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public Object detail(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}	
		
		return ResponseUtil.getObject(service.detail(id));
	}
	
	/**
	 * 新增拜访规则
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Object insert(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		VisitruleVO vo = getVisitruleVO(request);
		
		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		vo = service.insert(vo);
		
		if (vo.getId() == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "获取自增主键为空");
		}
		
		vo = getVisitruleDetail(vo.getId());
		
		return ResponseUtil.getObject(vo);
	}
	
	/**
	 * 修改拜访规则
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.PUT)
	public Object update(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}	

		VisitruleVO vo = getVisitruleVO(request);
		if (vo == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "转换实体失败");
		}
		
		vo.setId(id);
		
		String validMsg = validator(vo);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		service.update(vo);

		vo = getVisitruleDetail(id);
				
		return ResponseUtil.getObject(vo);
	}
	
	/**
	 * 批量删除拜访规则
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Object batchDelete(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idsStr = paramObj.getString("ids");		

		if (idsStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] idArray = idsStr.split(",");
		
		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		//校验是否被引用，提示：拜访规则正被引用，不允许删除
		
		@SuppressWarnings("unchecked")
		Page<VisitruleVO> page = service.batchDelete(idArray, getRequestPage(paramObj), (Map<String, Object>)paramObj.get("searchMap"));
				
		return ResponseUtil.getObject(page);
	}
	
	/**
	 * 批量停启用
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "state", method = RequestMethod.PUT)
	public Object batchUpdateEnableState(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		
		JSONObject paramObj = RequestUtil.getParamObject(request);
		String idStr = paramObj.getString("id");		

		if (idStr == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "ids参数为空");
		}
		
		String[] idArray = idStr.split(",");
		
		if (idArray.length == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "至少选中一条记录");
		}
		
		Integer enableState = paramObj.getInt("enableState");
		
		if (enableState == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "停启用状态不能为空");
		}
		
		//校验是否被引用，提示：拜访规则正被引用，不允许停用
		Map<String, Object> condMap = (Map<String, Object>) paramObj.get("searchMap");
		List<VisitruleVO> list = service.batchUpdateEnableState(idArray, enableState, condMap);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("voList", list);
		return ResponseUtil.getObject(result);
	}
	
	private Page<VisitruleVO> getRequestPage(JSONObject paramObj) throws CrmMessageException {
		
		Integer page = paramObj.getInt(HttpKeyConstant.Page);
		Integer pageSize = paramObj.getInt(HttpKeyConstant.PageSize);
		
		if (page == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "page不能为空");
		}
		
		if (pageSize == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "pageSize不能为空");
		}
		
		return new Page<VisitruleVO>(page, pageSize);
	}
	
	private String validator(VisitruleVO vo) {
		
		if (vo == null) {
			return "转换实体失败";
		}
		
		if (StringUtils.isBlank(vo.getName())) {
        	return  "名称不能为空";
		}
		
		if (vo.getRefIndex() == null) {
			return  "参考指标不能为空";
		}
		
		if (vo.getCumEnumValue() == null) {
			
			if (vo.getCumEnumValue() ==  RefIndexEnum.CUMLEVEL.getValue()) {
				return "客户等级不能为空";
			}
			else if (vo.getCumEnumValue() ==  RefIndexEnum.CUMTYPE.getValue()) {
				return "客户类型不能为空";
			}
			else if (vo.getCumEnumValue() ==  RefIndexEnum.CUMSTATE.getValue()) {
				return "客户状态不能为空";
			}
		}
		
		if (vo.getOrgId() == null) {
			return  "公司不能为空";
		}
		
		if (vo.getTaskcardList() == null || vo.getTaskcardList().size() == 0) {
			return "必须选择一个有效的任务卡";
		}

		return "";
	}
	
	private VisitruleVO getVisitruleVO(HttpServletRequest request) {
		
		Map<String, Class<?>> fieldClassMap = new HashMap<String, Class<?>>();
		fieldClassMap.put("taskcardList", VisitruleTaskcardVO.class);
		return RequestUtil.getVO(request, VisitruleVO.class, fieldClassMap);
	}
	
	private VisitruleVO getVisitruleDetail(Long id) {
		
		VisitruleVO vo = null;
		
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("id", id);
		
		Page<VisitruleVO> page = service.list(new Page<VisitruleVO>(1, 10), paraMap);
		if (page != null && page.getData() != null && page.getData().size() > 0) {
			vo = page.getData().get(0);
		}

		return vo;
	}
	
	/*********拜访规则2.0**********/
	/**
	 * 拜访规则列表
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Object list(HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {
		JSONObject paramObj = RequestUtil.getParamObject(request);
		@SuppressWarnings("unchecked")
		Map<String, Object> condMap = (Map<String, Object>) paramObj.get("searchMap");
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("voList", service.list(condMap));
		
		return ResponseUtil.getObject(result);
	}
	
	/**
	 * 保存任务卡
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws CrmMessageException
	 */
	@RequestMapping(value = "{id}/taskcards", method = RequestMethod.POST)
	public Object saveVT(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws CrmMessageException {

		if (id == null) {
        	throw new CrmMessageException(PCCodeConstant.ServerError, "主键不能为空");
		}	

		List<VisitruleTaskcardVO> voList = RequestUtil.getVOList(request, VisitruleTaskcardVO.class);
		
		String validMsg = validator(voList);
		if (!validMsg.equals("")){
        	throw new CrmMessageException(PCCodeConstant.ServerError, validMsg);
		}
		
		service.saveVT(voList, id);
				
		return ResponseUtil.getObject();
	}
	
	private String validator(List<VisitruleTaskcardVO> voList) {

		if (voList == null || voList.size() == 0) {
        	return "保存时，需要至少有一个任务卡";
		}
		
		StringBuffer msgBuffer = new StringBuffer();
		
		StringBuffer errorBuffer = new StringBuffer();
		
		for (int i=0; i<voList.size(); i++ ) {
			
			VisitruleTaskcardVO vo = voList.get(i);
			
			if (vo.getTaskcardId() == null) {
				errorBuffer.append("【任务卡id不能为空】");
			}
			
			if (vo.getRequired() == null) {
				errorBuffer.append("【必输不能为空】");
			}
			
			if (vo.getOrderNum() == null) {
				errorBuffer.append("【显示顺序不能为空】");
			}
			
			if (vo.getIsPreseted() == null) {
				errorBuffer.append("【预置字段不能为空】");
			}
			
			if (errorBuffer.length() > 0) {
				msgBuffer.append("第");
				msgBuffer.append(i+1);
				msgBuffer.append("行，");
				msgBuffer.append(errorBuffer);
				msgBuffer.append("\n");
			}

			errorBuffer.setLength(0);
		}
		
		return msgBuffer.toString();
	}
	
}
